<template>
    <search-table
        :columns="accessListColumns"
        :data="accessGroupList"
        :total="groupTotal"
        :page.sync="queryGroupInfo.pageIndex"
        :size.sync="queryGroupInfo.pageSize"
        @change-size="changeSize"
        @change-page="changePage"
    >
        <Alert type="error" show-icon v-if="showDuplicateNameTip" slot="alert">
            <p>不同小组中存在相同成员，请删除</p>
        </Alert>
        <template slot="button-group">
            <Button
                type="primary"
                ghost
                @click="openUserAccessModal"
                icon="md-add"
                :disabled="disabledAllBtn"
                >创建小组</Button
            >
        </template>
        <template slot="input-group">
            <Input v-model="teamName" placeholder="名称" @on-change="getDataBounce" clearable />
        </template>
        <Modal
            v-model="accessUserModal.show"
            :title="accessUserModal.title"
            :width="920"
            :loading="accessUserModal.loading"
            @on-cancel="refreshAccessGroupList"
            :mask-closable="false"
            footer-hide
        >
            <AccessUserTransfer
                :contentId="contentId"
                :selectGroup="currGroup"
                :show="accessUserModal.show"
            ></AccessUserTransfer>
        </Modal>
        <Modal
            v-model="accessGroupModal.show"
            :title="accessGroupModal.title"
            :width="600"
            @on-ok="addOrUpdateAccessGroup"
            @on-cancel="handleReset"
            @on-visible-change="visibleChange"
            :loading="accessGroupModal.loading"
            :mask-closable="false"
        >
            <Form
                ref="groupFormValidate"
                :model="groupFormValidate"
                :rules="groupRuleValidate"
                :label-width="80"
            >
                <FormItem label="名称" prop="name">
                    <Input
                        v-model.trim="groupFormValidate.name"
                        placeholder="请输入名称"
                        :maxlength="50"
                    ></Input>
                </FormItem>
                <FormItem label="描述" prop="description">
                    <Input
                        type="textarea"
                        :maxlength="200"
                        :rows="4"
                        v-model.trim="groupFormValidate.description"
                        placeholder="请输入描述"
                    ></Input>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="userModel" title="接入用户" width="550" footer-hide>
            <div class="userModel">
                <Tag
                type='border'
                :color="item.online ? 'primary' : 'error'"
                :name="item.id"
                v-for="(item, index) in userList"
                :key="index" >
                    <Icon type="ios-person-outline" size ='16'/>
                    <span
                    class="user_list_line"
                    :style="{borderLeft :item.online ? '1px dashed #2d8cf0': '1px dashed #ed4014'}"
                    ></span>
                    <span>{{ item.userName + '-' + (item.online ? '在线-' + item.ip : '离线') }}</span>
                    <span
                    class="user_list_line"
                    :style="{borderLeft :item.online ? '1px dashed #2d8cf0': '1px dashed #ed4014',display:(currGroup.userId === item.userId) || disabledAllBtn ? 'none' : ''}"
                    ></span>
                    <a @click="setGroupUser(currGroup,item)">设为组长</a>
                </Tag>
            </div>
        </Modal>
    </search-table>
</template>

<script>
import AccessUserTransfer from './accessUserTransfer.vue';
import {
    queryGroup,
    delGroupUser,
    delGroup,
    addGroup,
    updateGroup,
    // getUserInstanceExclude,
} from '../../api/group';
import {
    getUserLoginIP
} from '@/api/drill_compete';
import { getCompanyUsersInfo } from '@/api/users';
import { mapMutations } from 'vuex';
import { debounce } from '@/libs/utils';

export default {
    name: 'scenes',
    components: {
        AccessUserTransfer
    },
    props: {
        'disabledAllBtn':{
            type:Boolean,
            default:false
        }
    },
    mixins: [],
    data() {
        return {
            teamName: '', // 搜索条件，团队名称
            contentId: this.$route.query.id,
            currGroup: {},
            listStyle: {
                width: '290px',
                height: '300px',
            },
            usedAccessList: [],
            accessGroupList: [],
            accessGroupModal: {
                show: false,
                loading: true,
                title: '添加小组',
                type: 'add',
            },
            accessUserModal: {
                show: false,
                loading: true,
                title: '添加/移除用户',
            },
            queryGroupMemberInfo: {
                contentId: this.$route.query.id,
                pageIndex: 1,
                pageSize: 10,
            },
            groupMemberTotal: 0,
            projectGroupMemberList: [],
            groupFormValidate: {
                name: '',
                description: '',
            },
            groupRuleValidate: {
                name: [{ required: true, message: '不能为空', trigger: 'change' }],
                partyId: [{ required: true, message: '不能为空', trigger: 'change' }],
            },
            accessListColumns: [
                {
                    title: '名称',
                    key: 'name',
                    align: 'center',
                    width: 230,
                    placement: 'top-left',
                    order: 1,
                    tooltip: true,
                },
                {
                    title:'组长',
                    key:'userName',
                    tooltip:true
                },
                {
                    title:'组员',
                    key: 'userList',
                    align: 'center',
                    minWidth:300,
                    render: (h, params) => {
                        let copyList = Array.from(params.row.accessGroupUsers)
                        let arrEl = copyList && copyList.length > 3 ? copyList.slice(0, 2) : copyList
                        let arr = arrEl.map((user) => {
                            return h(
                                'Tag',
                                {
                                    props: {
                                        type: 'border',
                                        color: user.online ? 'primary' : 'error',
                                        name: user.id,
                                    },
                                },
                                [
                                    h('Icon', {
                                        attrs: {
                                            type: 'ios-person-outline',
                                            size: 16,
                                        },
                                        style: {
                                            'margin-top': '-2px',
                                        },
                                    }),
                                    h('span', {
                                        style: {
                                            display: 'inline-block',
                                            width: 0,
                                            height: '100%',
                                            margin: '0 8px',
                                            borderLeft: user.online
                                                ? '1px dashed #2d8cf0'
                                                : '1px dashed #ed4014',
                                            verticalAlign: 'middle',
                                        },
                                    }),
                                    h(
                                        'span',
                                        {},
                                        user.userName +
                                        '-' +
                                        (user.online ? '在线-' + user.ip : '离线')
                                    ),
                                    h('span', {
                                        style: {
                                            display:params.row.userId === user.userId ? 'none' : 'inline-block',
                                            width: 0,
                                            height: '100%',
                                            margin: '0 8px',
                                            borderLeft: user.online
                                                ? '1px dashed #2d8cf0'
                                                : '1px dashed #ed4014',
                                            verticalAlign: 'middle',
                                        },
                                    }),
                                    h('a',{
                                        props:{
                                            type:'primary'
                                        },
                                        style:{
                                            color:'var(--url-color)',
                                            fontWeight:'bold',
                                            display:(params.row.userId === user.userId) || this.disabledAllBtn ? 'none' : ''
                                        },
                                        on:{
                                            click:(e) => {
                                                this.setGroupUser(params.row,user)
                                            }
                                        }
                                    },'设为组长')
                                ]
                            );
                        });
                        return h(
                            'div',
                            {
                                style: {
                                    display: 'flex',
                                    'flex-wrap': 'wrap',
                                },
                            },
                            arr.length === 0 ? '-' : [arr, h('Button', {
                                props: {
                                    type: 'info',
                                    size: 'small',
                                    // disabled: params.row.userList && params.row.userList.length == 0
                                },
                                style: {
                                    display: copyList.length > 2 ? 'block' : 'none'
                                },
                                on: {
                                    click: () => {
                                        this.handleUserNumber(params.row.accessGroupUsers)
                                    }
                                }
                            }, '查看')]
                        );
                    },
                },
                {
                    title: '创建者',
                    key: 'creatorName',
                    align: 'center',
                    width: 120,
                    tooltip: true,
                },
                {
                    title: '创建时间',
                    key: 'createTime',
                    align: 'center',
                    minWidth:140,
                },
                {
                    title: '操作',
                    width: 200,
                    key: 'action',
                    opList: [
                        {
                            txt: '添加组员',
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            fun: (data) => {
                                this.currGroup = data;
                                this.accessUserModal.show = true;
                            }
                        },
                        {
                            txt: '修改',
                            type: 'modify',
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            fun: (data) => {
                                this.accessGroupModal.type = 'modify';
                                this.accessGroupModal.title =
                                   this.type === 10 ? '修改角色 ' : '修改团队';
                                this.accessGroupModal.show = true;
                                this.groupFormValidate = {
                                    id: data.id,
                                    name: data.name,
                                    description: data.description
                                };
                            }
                        },
                        {
                            txt: '删除',
                            tooltip: true,
                            type: 'delete',
                            title: '确认删除？',
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            fun: this.delAccessGroup
                        }
                    ]
                }
            ],
            queryGroupInfo: {
                pageIndex: 1,
                pageSize: 10,
                contentId: this.$route.query.id,
            },
            groupTotal: 0,
            userModel: false,
            userList: [],
            showDuplicateNameTip:false,
            allSelUserIds:[]
        };
    },
    filters: {},
    computed: {
    },
    mounted() {
        this.getAccessGroupList();
    },
    methods: {
        handleUserNumber (item) {
            this.userModel = true
            this.currGroup = item
            this.userList = item
        },
        // 下拉框关闭时，点击body，让输入框失去焦点，用来修复iview表单中下拉框的怪异bug
        uncheck(type) {
            if (!type) {
                document.body.click();
            }
        },
        // 防抖封装，团队名改变时，延迟更新列表数据
        getDataBounce: debounce(function () {
            this.changePage();
        }),
        // 打开添加模态框，查询所有势力方和已使用的接入组
        openUserAccessModal() {
            this.accessGroupModal.show = true;
            this.accessGroupModal.type = 'add';
            this.accessGroupModal.title = '添加小组';
        },
        // 接入/移除用户的模态框隐藏后，更新接入组数据，通知vuex查询更新相关数据
        refreshAccessGroupList() {
            this.getAccessGroupList();
        },
        // 查询竞赛、演练接入组列表
        getAccessGroupList() {
            if (!this.contentId) {
                return;
            }
            queryGroup(
                Object.assign(this.queryGroupInfo, {
                    name: this.teamName,
                })
            ).then((data) => {
                if (data.code == 1) {
                    this.accessGroupList = data.data.items;
                    this.groupTotal = data.data.total;
                    this.accessGroupList.forEach((group) => {
                        let userList = group.accessGroupUsers;
                        let userIds = userList.map((user) => user.userId);
                        userList.forEach((user) => {
                            this.getCompanyUsersInfo(user.userId).then((online) => {
                                // 获取在线状态
                                this.$set(user, 'online', online);
                            });
                        });
                        this.getUserLoginIP(userIds).then((data) => {
                            // 获取用户登录IP地址
                            userList.forEach((user) => {
                                this.$set(user, 'ip', '');
                                if (data.length > 0) {
                                    let ips = data
                                        .filter((item) => item.userId == user.userId)
                                        .map((item) => item.loginIpAddress);
                                    if (ips.length > 0) {
                                        this.$set(user, 'ip', ips[0]);
                                    }
                                }
                            });
                        });
                    });
                    if (this.step == 'pre') {
                        // 赛前，人员有变化发送事件，提示需要重新交验是否可以开始竞赛或演练
                        this.$emit('setHasUser', '');
                    }
                } else if (data.code == -2) {
                    this.accessGroupList = [];
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 修改当前页，默认首页
        changePage(page = 1) {
            this.queryGroupInfo.pageIndex = page;
            this.getAccessGroupList();
        },
        // 修改分页大小，默认10条数据
        changeSize(size = 10) {
            this.queryGroupInfo.pageSize = size;
            this.getAccessGroupList();
        },
        // 获取已经使用的接入组，和所有势力方，可用于判断是否需要禁用添加团队按钮
        getAllAccessList() {
            if (!this.contentId) {
                return;
            }
            let params = {
                pageIndex: 1,
                pageSize: 2147483647,
                contentId: this.$route.query.id,
            };
            this.allPartyAreDisabled = false;
            // 查询已有的接入组，判断接入组成员是否重复
            queryGroup(params).then((data) => {
                if (data.code === 1) {
                    this.usedAccessList = data.data.items;
                    let allSelUserIds = [
                        ...this.usedAccessList
                            .map((team) => team.accessGroupUsers.map((user) => user.userId))
                            .flat(),
                    ];
                    this.allSelUserIds = allSelUserIds;
                    if ([...new Set(allSelUserIds)].length != allSelUserIds.length) {
                        // 组中成员有重复
                        this.showDuplicateNameTip = true;
                    } else {
                        this.showDuplicateNameTip = false;
                    }
                } else {
                    this.$Message.error(data.data.message);
                }
            });
        },
        // 清空团队添加、修改模态框的数据和校验信息
        handleReset() {
            this.$refs['groupFormValidate'].resetFields();
        },
        // 隐藏模态框时的回调函数
        visibleChange(type) {
            if (!type) {
                this.handleReset();
            }
        },
        // 添加或修改团队
        addOrUpdateAccessGroup() {
            if (!this.contentId) {
                // 场景id
                return;
            }
            this.$refs['groupFormValidate'].validate((valid) => {
                if (valid) {
                    let params = {
                        contentId: this.contentId,
                        name: this.groupFormValidate.name,
                        description: this.groupFormValidate.description,
                    };
                    if (this.accessGroupModal.type == 'add') {
                        // 添加操作
                        addGroup(params).then((data) => {
                            if (data.code == 1) {
                                this.$Message.info('添加小组成功');
                                this.teamName = '';
                                this.accessGroupModal.show = false;
                                this.getAccessGroupList();
                            } else {
                                this.cancelLoading('accessGroupModal');
                                this.$Message.warning(data.message);
                            }
                        });
                    } else {
                        updateGroup(this.groupFormValidate.id, params).then((data) => {
                            if (data.code == 1) {
                                this.accessGroupModal.show = false;
                                this.getAccessGroupList();
                            } else {
                                setTimeout(() => {
                                    this.cancelLoading('accessGroupModal');
                                }, 500);
                                this.$Message.warning(data.message);
                            }
                        });
                    }
                } else {
                    this.cancelLoading('accessGroupModal');
                }
            });
        },
        setGroupUser(group,user){
            updateGroup(group.id, {...group,userId:user.userId}).then((data) => {
                if (data.code == 1) {
                    this.$Message.info('设置成功');
                    this.getAccessGroupList();
                }
            });
        },
        // 删除团队
        delAccessGroup(group) {
            // let userIds = group.userList.map((user) => user.userId);
            delGroup(group.id).then((data) => {
                if (data.code == 1) {
                    this.$Message.info('删除小组成功');
                    // 删除后展示当前页，当前页没有数据展示前一页
                    this.queryGroupInfo.pageIndex =
                        this.accessGroupList.length == 1 && this.queryGroupInfo.pageIndex > 1
                            ? this.queryGroupInfo.pageIndex - 1
                            : this.queryGroupInfo.pageIndex;
                    this.getAccessGroupList();
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 删除团队下已分配的目标
        delTeamTarget(sceneId, teamId) {
            delTeamTarget(sceneId, teamId)
                .then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('删除团队下已分配的目标异常');
                });
        },
        // 夺旗赛删除已经分配的题目
        delAssignedTopics(teamId) {
            delAssignedTopics(this.$route.query.id, teamId)
                .then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('删除团队下已分配的靶机异常');
                });
        },
        // 切换环境时，切换虚拟机
        deviceToUser(group, user, vms) {
            return new Promise((resolve, reject) => {
                let devices = [];
                devices = vms.map((vm) => {
                    return {
                        deviceId: vm.id,
                        deviceName: vm.name,
                        deviceType: 'VM',
                        enableRecordScreen: true,
                        enabled: true,
                    };
                });
                let params = {
                    accessGroupId: group.id,
                    devices: devices,
                    contentId: this.$route.query.id,
                    userId: user.userId,
                };
                setuservmrelation(params).then((data) => {
                    if (data.code == 1) {
                        resolve();
                    } else {
                        reject(data.message);
                        this.$Message.warning(data.message);
                    }
                });
            });
        },
        // 模态框切换loading状态，使确定按钮可以点击
        cancelLoading(name) {
            this[name].loading = false;
            setTimeout(() => {
                this[name].loading = true;
            });
        },
        // 删除场景中的接入用户
        delSceneUsers(userIds) {
            delGroupUser(this.contentId, userIds).then((data) => {
                if (data.code == 1) {
                    if (!this.delTeam) {
                        // 删除团队的操作时，不需要提示信息
                        this.$Message.info('操作成功');
                    }
                    // 操作结束后，重置delTeam
                    this.delTeam = false;
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 查询工程详情
        getProjectInfo() {
            getstatusbyprjid(this.$route.query.prjid).then((data) => {
                if (data.code == 1) {
                    this.projectInfo = data.attribute;
                    this.getProjectSubnet();
                }
            });
        },
        // 获取返回用户的在线状态
        getCompanyUsersInfo(userId) {
            return new Promise((resolve, reject) => {
                getCompanyUsersInfo(userId).then((data) => {
                    if (data.code == 1) {
                        resolve(data.data.online);
                    } else {
                        // 查询有误时，特意不提示错误信息，无法展示在线状态即可，避免查看非自身单位的人员出现错误提示。
                        resolve(false);
                    }
                });
            });
        },
        // 获取用户登录ip
        getUserLoginIP(userIds) {
            return new Promise((resolve, reject) => {
                getUserLoginIP(userIds).then((data) => {
                    if (data.code == 1) {
                        // 降序排列，便于拿到最近的登陆时间
                        resolve(
                            data.data.sort(
                                (a, b) =>
                                    new Date(b.loginTime).getTime() -
                                    new Date(a.loginTime).getTime()
                            )
                        );
                    } else {
                        this.$Message.warning(data.message);
                        resolve('');
                    }
                });
            });
        },
        // 导出用户信息，当前版本该功能暂时隐藏
        doOutputUser() {
            let projectId = this.$route.query.prjid;
            outputUser(projectId).then((data) => {
                let url = window.URL.createObjectURL(data); //表示一个指定的file对象或Blob对象
                let a = document.createElement('a');
                document.body.appendChild(a);
                let fileName = this.$route.query.name + '用户下载.xls'; //filename名称截取
                a.href = url;
                a.download = fileName; //命名下载名称
                a.click(); //点击触发下载
                window.URL.revokeObjectURL(url); //下载完成进行释放
            });
        },
    },
};
</script>

<style scoped>
#accessUser .userModel{
    display: flex;
    flex-wrap: wrap;
}
.userModel .user_list_line{
    display: inline-block;
    width: 0;
    height: 100%;
    margin: 0 8px;
    vertical-align: middle;
}
</style>
<style>
#access .demo-table-info-row > td {
    background: lightblue;
}
#access .ivu-table-overflowX {
    overflow-x: hidden;
}
</style>
